package com.camemax.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.camemax.server.pojo.Orders;
import com.camemax.server.service.OrdersRabbitmqService;
import com.camemax.server.service.OrdersService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

// ************************
// * @Date: 2021/6/21
// * @Author: Camemax
// * @Description: 订单服务实现类 - 实现Rabbitmq写入业务代码
// ************************
@Service("ordersRabbitmqService")
public class OrdersRabbitmqServiceImpl implements OrdersRabbitmqService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrdersService service;

    @PostConstruct
    public void publisherConfirm(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * @param correlationData: 表示消息的唯一性 - 唯一id;
             * @param ack: 响应的结果，true表示消息入队成功，false表示失败;
             * @param cause: 操作结果
             * */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                String orderId = correlationData.getId();
                // 判断订单信息是否成功写入rabbitmq中，如写入成功则返回ack（即ack=true）
                if ( !ack ){
                    System.out.println("Rabbitmq-Publisher 响应失败，请稍后再试！");
                    return;
                }

                int resultCount = service.updateRedundancyOrderStatus(orderId);
                if (resultCount == 1){
                    System.out.println("订单信息保存Rabbitmq成功！");
                }
            }
        });
    }

    @Override
    public void sendMessage(Orders order) {
        String exchange = "orders-fanout-exchange";
        String routingKey = "";
        // JSON序列化订单信息
        String serializedOrderInfo = JSONObject.toJSONString(order);
        // 将序列化后的订单信息写入Rabbitmq
        rabbitTemplate.convertAndSend(exchange, routingKey, serializedOrderInfo, new CorrelationData(order.getOrderId()));
    }
}
